package com.citytechinc.cmis.client.service
{
	import com.citytechinc.cmis.client.event.RepositoryInfoEvent;
	import com.citytechinc.cmis.client.model.Property;
	import com.citytechinc.cmis.client.model.Repository;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	public class RepositoryInfoService extends EventDispatcher
	{
		private namespace app = "http://www.w3.org/2007/app";
		private namespace atom = "http://www.w3.org/2005/Atom";
		private namespace cmis = "http://www.cmis.org/2008/05";
		
		use namespace app;
        use namespace atom;
        use namespace cmis;
        
		private var auth:String;
		
		public function RepositoryInfoService(auth:String)
		{
			this.auth = auth;
		}
		
		public function getRepositoryInfo(url:String):void 
		{
			var service:HTTPService = new HTTPService();

			service.url = url;
			service.resultFormat = "e4x";
			service.addEventListener(ResultEvent.RESULT, setRepositoryInfo)
			service.headers["Authorization"] = "Basic " + auth;
			
			service.send();
		}
		
		private function setRepositoryInfo(event:ResultEvent):void
		{
			var properties:ArrayCollection = new ArrayCollection();
			var capabilities:ArrayCollection = new ArrayCollection();
			
			for each(var p:XML in event.result.workspace.repositoryInfo.children())
				if (p.hasSimpleContent())
					properties.addItem(Property.getProperty(p));
			
			for each(var c:XML in event.result.workspace.repositoryInfo.capabilities.children()) 
				capabilities.addItem(Property.getProperty(c));
				
			var queryURL:String = event.result.workspace.collection.(@collectionType=='query').@href;
			var childrenURL:String = event.result.workspace.collection.(@collectionType=='root-children').@href;
			var typesURL:String = event.result.workspace.collection.(@collectionType=='types-descendants').@href;
			
			var repository:Repository = new Repository();
			
			repository.properties = properties;
			repository.capabilities = capabilities;
			
			repository.queryURL = queryURL;
			repository.childrenURL = childrenURL;
			repository.typesURL = typesURL;
			
			this.dispatchEvent(new RepositoryInfoEvent(RepositoryInfoEvent.INFO, repository));
		}

	}
	
}